package com.ssmdemo.controller;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.plugins.Page;
import com.ssmdemo.aop.bean.PermissionCode;
import com.ssmdemo.pojo.Dept;
import com.ssmdemo.pojo.Emp;
import com.ssmdemo.service.DeptService;
import com.ssmdemo.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/getDept")
public class GetDeptList {
    @Autowired
    DeptService deptService;

    @RequestMapping("/getDeptList")
    @PermissionCode(value = "dept:list")
    public String getEmpList(Page<Dept> page,Model model){
        page=deptService.selectDeptPage(page);
        model.addAttribute("url","getDeptList");
        model.addAttribute("page",page);
        return "dept/deptList";
    }

    @RequestMapping("/toAddDept")
    public String toAddEmp(){
        return "dept/addDept";
    }
    @RequestMapping("/toUpdateDept/{id}")
    public String toUpdateEmp(@PathVariable Integer id, Model model){
        Dept dept =deptService.selectById(id);
        dept.setParentDept(deptService.selectById(dept.getParentId()));
        model.addAttribute("dept",dept);
        return "dept/updateDept";
    }

    @RequestMapping("/getAddDept")
    public String getAddEmp(Dept dept){

//        deptService.insert(dept);
        deptService.insertDept(dept);
        return "redirect:getDeptList";
    }
    @RequestMapping("/getUpdateDept")
    public String getUpdateEmp(Dept dept){

//        System.out.println(dept.toString());
        deptService.updateDept(dept);
        return "redirect:getDeptList";
    }

    @RequestMapping("/bacthDelectDept")
    public String bacthDelectEmp(@RequestParam("d[]") List d){

        deptService.deleteBatchIds(d);
        return "redirect:getDeptList";
    }

    @RequestMapping("/getDeptListByParentId")
    @ResponseBody
    public List<Map<String,Object>> getDeptListByParentId(Integer id){

        if (id==null){
            id=0;
        }

        List<Dept> list=deptService.getDeptListByPerentId(id);


        List<Map<String,Object>> mapList=new ArrayList<Map<String, Object>>();

        for (Dept dept:list){

            Map<String,Object> map=new HashMap<String, Object>();
            map.put("name",dept.getDeptName());
            map.put("id",dept.getId());
            map.put("isParent",dept.getSubId()!=null?true:false);
            mapList.add(map);
        }

        return mapList;

    }
}
